from datetime import datetime, timedelta
import random

from django.http import JsonResponse
from django.shortcuts import render, redirect
import logging
from .models import Item

logger = logging.getLogger('custom')


def index_1(request):
    """主页面"""
    all_items = Item.objects.all()
    # all_items = Item.objects.filter(register_name="阿里巴巴", license_num='*')
    context = {'all_items': all_items}
    return render(request, 'project/index.html', context=context)


def create(request):
    """创建"""
    if request.method == 'GET':
        return render(request, 'project/add.html')

    if request.method == 'POST':
        register_name = request.POST.get('register_name')
        license_num = request.POST.get('license_num')
        payment_account = request.POST.get('payment_account')
        remark = request.POST.get('remark', '')
        # is_print = request.POST.get('is_print')
        # is_abandon = request.POST.get('is_abandon')

        params = {
            # 'receipt': datetime.now().strftime('%Y%m%d'),
            'register_name': register_name,
            'license_num': license_num,
            'payment_account': payment_account,
            'remark': remark,
            # 'is_print': is_print,
            # 'is_abandon': is_abandon,
        }
        q = Item.objects.create(**params)
        _id = q.id
        if q.id < 1000:
            end = str(_id).zfill(4)
        else:
            end = str(_id)[-4:]

        q.receipt = datetime.now().strftime('%Y%m%d') + end
        q.save()
        return JsonResponse({'code': 0, 'msg': 'ok'})


def update(request):
    """修改"""
    if request.method == 'GET':
        try:
            item_id = request.GET.get('id')
            item = Item.objects.filter(id=item_id).first()
            return render(request, 'project/update.html', context={'item': item})
        except Exception as e:
            print(e)

    if request.method == 'POST':
        id = request.POST.get('id')

        item = Item.objects.filter(id=id).first()
        if item.is_print:
            return JsonResponse({'code': -1, 'msg': '已打印不能修改'})

        register_name = request.POST.get('register_name')
        license_num = request.POST.get('license_num')
        payment_account = request.POST.get('payment_account')
        remark = request.POST.get('remark')
        # is_abandon = request.POST.get('is_abandon')
        # is_print = request.POST.get('is_print')

        params = {
            'register_name': register_name,
            'license_num': license_num,
            'payment_account': payment_account,
            'remark': remark,
            # 'is_abandon': is_abandon,
            # 'is_print': is_print,
        }
        Item.objects.filter(id=id).update(**params)
        return JsonResponse({'code': 0, 'msg': 'ok'})


def abandon(request):
    """作废操作:批量"""
    _id = request.GET.get('id', [])
    print("—-作废id:", _id)
    if not _id:
        return JsonResponse({'code': -1, 'msg': '访问出错！'})
    try:
        Item.objects.filter(id=_id).update(is_abandon=1)
        return JsonResponse({'code': 0, 'msg': ''})
    except Exception as e:
        logger.error("作废失败：{0}".format(str(e)))
        return JsonResponse({'code': -1, 'msg': '无法设置作废，请刷新重试'})


def del_item(request):
    """
    :param request:
    :return:
    """
    _id = request.GET.get('id')

    if not _id:
        return JsonResponse({'code': -1, 'msg': '访问出错！'})
    try:
        item = Item.objects.filter(id=_id).first()
        if item.is_print == 1 and item.is_abandon == 0:
            return JsonResponse({'code': -1, 'msg': '已打印未作废不能删除'})
        else:
            item.delete()
        return JsonResponse({'code': 0, 'msg': 'ok'})
    except Exception as e:
        logger.error("删除失败：{0}".format(str(e)))
        return JsonResponse({'code': -1, 'msg': '无法删除，请刷新重试！'})


def change_print(request):
    if request.method != 'GET':
        return JsonResponse({'code': 400, 'msg': '请求失败！'})

    _id = request.GET.get('id')
    try:
        Item.objects.filter(id=_id).update(is_print=1)
    except Exception as e:
        logger.error("设置打印状态错误")
        return JsonResponse({'code': -1, 'msg': '无法打印，请刷新重试'})
    return JsonResponse({'code': 0, 'msg': 'ok'})


def index(request):
    """
    过滤功能
    :param request:
    :return:
    """
    if request.method == 'GET':
        all_items = Item.objects.filter()
        # all_items = Item.objects.filter(register_name="阿里巴巴", license_num='*')
        context = {'all_items': all_items, 'total': all_items.count()}
        return render(request, 'project/index.html', context=context)

    try:
        if request.method == 'POST':
            register_name = request.POST.get('register_name', '')
            license_num = request.POST.get('license_num', '')
            payment_account = request.POST.get('payment_account', "")
            logmin = request.POST.get('logmin', '')
            logmax = request.POST.get('logmax', '')
            old_logmax = logmax
            if logmax:
                logmax = datetime.strptime(logmax, '%Y-%m-%d') + timedelta(days=1)

            params = {}
            if register_name:
                params['register_name'] = register_name
            if license_num:
                params['license_num'] = license_num
            if payment_account:
                params['payment_account'] = payment_account

            print(params)
            if not params:
                queryset = Item.objects.filter()
            else:
                queryset = Item.objects.filter(**params).filter()

            if logmin and logmax:
                queryset = queryset.filter(create_time__range=(logmin, logmax)).filter(is_abandon=0)
                params['logmin'] = logmin
                params['logmax'] = old_logmax

            context = {'all_items': queryset, 'params': params , 'total': queryset.count()}
            return render(request, 'project/index.html', context=context)
    except Exception as e:
        logger.error(e)
        return JsonResponse({'code': -1, "msg": '系统错误！'})


def searching(request):
    """
    过滤功能
    :param request:
    :return:
    """
    if request.method == 'GET':
        all_items = Item.objects.filter()
        # all_items = Item.objects.filter(register_name="阿里巴巴", license_num='*')
        context = {'all_items': all_items}
        return render(request, 'project/index.html', context=context)

    try:
        if request.method == 'POST':
            register_name = request.POST.get('register_name', '')
            license_num = request.POST.get('license_num', '')
            payment_account = request.POST.get('payment_account', "")
            logmin = request.POST.get('logmin', '')
            logmax = request.POST.get('logmax', '')
            old_logmax = logmax
            if logmax:
                logmax = datetime.strptime(logmax, '%Y-%m-%d') + timedelta(days=1)

            params = {}
            if register_name:
                params['register_name'] = register_name
            if license_num:
                params['license_num'] = license_num
            if payment_account:
                params['payment_account'] = payment_account

            print(params)
            if not params:
                queryset = Item.objects.filter()
            else:
                queryset = Item.objects.filter(**params).filter()

            if logmin and logmax:
                queryset = queryset.filter(create_time__range=(logmin, logmax)).filter()
                params['logmin'] = logmin
                params['logmax'] = old_logmax

            context = {'all_items': queryset, 'params': params , 'total': queryset.count()}
            return render(request, 'project/index.html', context=context)
    except Exception as e:
        logger.error(e)
        return JsonResponse({'code': -1, "msg": '系统错误！'})


def export(request):
    """
    导出excel的数据，由前端导出
    :param request:
    :return:
    """
    if request.method == 'POST':
        register_name = request.POST.get('register_name', '')
        license_num = request.POST.get('license_num', '')
        payment_account = request.POST.get('payment_account', "")
        logmin = request.POST.get('logmin', '')
        logmax = request.POST.get('logmax', '')
        old_logmax = logmax
        if logmax:
            logmax = datetime.strptime(logmax, '%Y-%m-%d') + timedelta(days=1)

        params = {}
        if register_name:
            params['register_name'] = register_name
        if license_num:
            params['license_num'] = license_num
        if payment_account:
            params['payment_account'] = payment_account

        print(params)
        if not params:
            queryset = Item.objects.filter(is_abandon=0)
        else:
            queryset = Item.objects.filter(**params).filter(is_abandon=0)

        if logmin and logmax:
            queryset = queryset.filter(create_time__range=(logmin, logmax)).filter(is_abandon=0)
            params['logmin'] = logmin
            params['logmax'] = old_logmax

        filename = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(100, 999)) + '.xlsx'

        result = [item.to_dict() for item in queryset]
        return JsonResponse({'data': result, 'code': 0, 'msg': 'ok', 'filename': filename, 'total': queryset.count()})



# def page_not_found(request):
#     return render(request, '404.html')
#
#
# def server_error(request):
#     return render(request, '500.html')





